package com.csf.common.protobuff.deseralizer;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.ssl.SslHandler;

import com.csf.common.message.TestMessage.Test;
import com.csf.common.utils.Greeter;


public class ProtoBuffDeserialiser extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger
			.getLogger(ProtoBuffDeserialiser.class.getName());

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		System.out.println("Message received in Server : ");
		ChannelBuffer cb = ((ChannelBuffer) e.getMessage());
		byte bytes[] = cb.array();
		try {

			Test t = Test.parseFrom(bytes);
			System.out.println("Message from Client : id " + t.getId() + "name"
					+ t.getName());

			Test t1 = Test.newBuilder().setId(t.getId() + 100).setName(
					t.getName() + "server").build();

			System.out.println("Sending response from Server");
			e.getChannel().write(t1.toByteArray());
		}

		catch (Exception exp) {
			exp.printStackTrace();
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		logger.log(Level.WARNING, "Unexpected exception from downstream.", e
				.getCause());
		e.getChannel().close();
	}

	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {

		System.out.println("channel connected");

		// Get the SslHandler in the current pipeline.
		// We added it in SecureChatPipelineFactory.
		final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);

		// Get notified when SSL handshake is done.
		ChannelFuture handshakeFuture = sslHandler.handshake();
		handshakeFuture.addListener(new Greeter(sslHandler));
	}

}
